const mongoose = require('mongoose');

// MongoDB连接配置
const MONGODB_URI = 'mongodb+srv://2264521353:1234567890@six0.hic1spu.mongodb.net/Maintenance';
const DB_NAME = 'Maintenance';

// 连接选项
const options = {
  serverSelectionTimeoutMS: 10000, // 服务器选择超时
  socketTimeoutMS: 45000, // Socket超时
  connectTimeoutMS: 10000, // 连接超时
  heartbeatFrequencyMS: 2000, // 心跳频率
  maxPoolSize: 10, // 最大连接池大小
  minPoolSize: 1, // 最小连接池大小
  maxIdleTimeMS: 30000, // 最大空闲时间
  retryWrites: true,
  w: 'majority'
};

// 数据库连接函数
const connectDB = async () => {
  try {
    await mongoose.connect(MONGODB_URI, options);
    console.log('✅ MongoDB 连接成功');
    console.log('📍 数据库:', DB_NAME);
    console.log('🔗 连接状态:', mongoose.connection.readyState === 1 ? '已连接' : '未连接');
  } catch (error) {
    console.error('❌ MongoDB 连接失败:', error.message);
    // 在生产环境中，可能需要退出进程
    if (process.env.NODE_ENV === 'production') {
      process.exit(1);
    }
  }
};

// 监听数据库连接事件
mongoose.connection.on('connected', () => {
  console.log('🔗 Mongoose 已连接到 MongoDB');
});

mongoose.connection.on('error', (err) => {
  console.error('❌ Mongoose 连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('🔌 Mongoose 连接已断开');
});

// 优雅关闭数据库连接
const gracefulShutdown = async (msg, callback) => {
  try {
    await mongoose.connection.close();
    console.log(`🔌 Mongoose 连接已关闭: ${msg}`);
    callback();
  } catch (error) {
    console.error('🔌 数据库关闭错误:', error);
    callback();
  }
};

// 监听进程终止信号
process.once('SIGUSR2', () => {
  gracefulShutdown('nodemon restart', () => {
    process.kill(process.pid, 'SIGUSR2');
  });
});

process.on('SIGINT', () => {
  gracefulShutdown('app termination', () => {
    process.exit(0);
  });
});

process.on('SIGTERM', () => {
  gracefulShutdown('Heroku app shutdown', () => {
    process.exit(0);
  });
});

module.exports = {
  connectDB,
  mongoose
};
